package com.zhihuishu.micro.course.openapi.course.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.zhihuishu.micro.course.model.ScoreAssessRule;
import com.zhihuishu.micro.course.openapi.course.ScoreAssessRuleOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.ScoreAssessRuleOpenDto;
import com.zhihuishu.micro.course.service.ScoreAssessRuleService;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

@Service("scoreAssessRuleOpenService")
public class ScoreAssessRuleOpenServiceImpl implements ScoreAssessRuleOpenService{
	
	@Autowired
	private ScoreAssessRuleService scoreAssessRuleService;

	@Override
	public RemoteResult<ScoreAssessRuleOpenDto> findByCourseId(Long courseId) {
		
		RemoteResult<ScoreAssessRuleOpenDto> result = new RemoteResult<ScoreAssessRuleOpenDto>();
		
		try {
			ScoreAssessRule scoreAssessRule = scoreAssessRuleService.findByCourseId(courseId);
			result.setResult(null == scoreAssessRule ? null : BeanHelper.transTo(scoreAssessRule,ScoreAssessRuleOpenDto.class));
			result.setSuccess(true);
		} catch (Exception e) {
			result.setResult(null);
			result.setSuccess(false);
			result.setExceptionStack(e);
		}
		
		return result;
	}

	@Override
	public RemoteResult<ScoreAssessRuleOpenDto> saveOrUpdate(ScoreAssessRuleOpenDto scoreAssessRuleOpenDto) throws RemoteException{
		Assert.notNull(scoreAssessRuleOpenDto,"scoreAssessRuleOpenDto must not be null");
		RemoteResult<ScoreAssessRuleOpenDto> result = new RemoteResult<ScoreAssessRuleOpenDto>();
		
		try {
			ScoreAssessRule scoreAssessRule = BeanHelper.transTo(scoreAssessRuleOpenDto,ScoreAssessRule.class);
			
			if (null == scoreAssessRule.getId()) {
				if(scoreAssessRule.getMarkRole() == null){
					scoreAssessRule.setMarkRole(2);
				}
				scoreAssessRule = scoreAssessRuleService.save(scoreAssessRule);
			} else {
				scoreAssessRule = scoreAssessRuleService.update(scoreAssessRule);
			}
			
			result.setResult(null == scoreAssessRule ? null : BeanHelper.transTo(scoreAssessRule,ScoreAssessRuleOpenDto.class));
			result.setSuccess(true);
		} catch (Exception e) {
			result.setResult(null);
			result.setSuccess(false);
			result.setExceptionStack(e);
		}
		
		return result;
	}
	
	@Override
	public RemoteResult<Boolean> remove(Long courseId) {
		
		RemoteResult<Boolean> result = new RemoteResult<Boolean>();
		
		try {
			scoreAssessRuleService.remove(courseId);
			result.setResult(true);
			result.setSuccess(true);
		} catch (Exception e) {
			result.setResult(false);
			result.setSuccess(false);
			result.setExceptionStack(e);
		}
		
		return result;
	}

}
